package com.supermap.wzhy.module.user.service;

import com.supermap.wzhy.common.entity.VoDiff;
import com.supermap.wzhy.common.service.BaseService;
import com.supermap.wzhy.data.ExcelUtil;
import com.supermap.wzhy.data.MD5Util;
import com.supermap.wzhy.data.PageInfo;
import com.supermap.wzhy.data.UserInfo;
import com.supermap.wzhy.data.cons.UserType;
import com.supermap.wzhy.entity.*;
import com.supermap.wzhy.module.sys.dao.RegionCatalogsDao;
import com.supermap.wzhy.module.sys.dao.RegionInfoDao;
import com.supermap.wzhy.module.user.dao.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by W.Hao on 14-2-26.
 */
@Service
public class UserService extends BaseService{

    @Autowired
    UserDao userDao;
    @Autowired
    RegionCatalogsDao regionCatalogsDao ;
    @Autowired
    RegionInfoDao regionInfoDao ;
    @Autowired
    UserMajorDao userMajorDao ;
    @Autowired
    UserMajorRelationDao userMajorRelationDao ;
    @Autowired
    UserRoleDao userRoleDao ;
    @Autowired
    UserRoleRelationDao userRoleRelationDao;

    /**
     * 用户列表
     * @param sql
     * @param pageInfo
     * @return
     */
    public List<TUsers> getAll(String sql, PageInfo pageInfo){
        return this.userRoleDao.queryEntityByPage(sql,TUsers.class,pageInfo);
    }
    public int size(String sql){
        return this.userRoleDao.findCountBySql(sql);
    }

    /**
     * 创建用户
     *
     * @param entity
     *          若roleid存在，则添加用户的角色
     * @return
     */
    public boolean create(TUsers entity) {
        if(entity!=null){
            //密码默跟登录名一样
            entity.setPassword(MD5Util.encode(entity.getUserName()));
            userDao.save(entity);
            return true;
        }
        return false;
    }

    /**
     * 批量创建用户
     * @param catalogId
     * @param level
     * @param password
     * @param sys_role
     * @param roleid
     *          若不为空，则创建统一角色
     * @return
     */
    public int createByLevel(int catalogId,int level,String password,int sys_role,int roleid){
        int re = 0;
        TRegioncatalog catalog = regionCatalogsDao.getOne(catalogId);
        if(null == catalog ){ return  re ;}
        TUserrole role = userRoleDao.findOne(roleid);   //找到角色记录

        List<TRegioninfo> regions = regionInfoDao.findByRegionlevel(catalogId,"%%",level);
        for(TRegioninfo r:regions){
            TUsers u = new TUsers();
            u.setUserName(r.getRegioncode());
            u.setPassword(MD5Util.encode(password != null ? password : r.getRegioncode()));
            u.setUserCaption(r.getName());
            u.setUserRegion(r.getName()+"@"+r.getRegioncode());
//            u.setSys_role(sys_role);
            u.setStatus(1);  //默认可用
            if(checkUserNameExists(u.getUserName())){ continue; }
            userDao.save(u);

            //若不为空，则创建统一角色
            if(role != null){
                TUserrolerelation turla = new TUserrolerelation(u,role);
                userRoleRelationDao.save(turla);
            }

            re++ ;
        }
        return  re ;
    }

    public int delete(String id) {
        int re = 0;
        String[] ids = id.split(",");
        for(String userid:ids){
            TUsers user = userDao.findOne(Integer.parseInt(userid));
            if(user!=null){
                userDao.delete(user);
                re++;
            }
        }
        return  re;
    }

    public boolean update(TUsers entity) {
        int id = entity.getUserid();
        TUsers user = userDao.findOne(id);
        if(user!=null){
            //原密码不进行转码 新密码才需要转码 用户不会要设置32位的密码吧 前端可以进行小于32位的限制
            /*if(entity.getPassword().length() != 32){
                entity.setPassword(MD5Util.encode(entity.getPassword()));
            }*/
            VoDiff<TUsers> diff = new VoDiff<>();
            try {
                diff.diff(user,entity);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            userDao.save(user);
            return true;
        }
        return false;
    }

    public boolean rePassword(int id, String password) {
        TUsers user = userDao.findOne(id);
        if(user!=null){
            //原密码不进行转码 新密码才需要转码 用户不会要设置32位的密码吧 前端可以进行小于32位的限制
            if(password.length() < 32){
                user.setPassword(MD5Util.encode(password));
            }

            userDao.save(user);
            return true;
        }
        return false;
    }

    public boolean simpleUpdate(TUsers entity){
        userDao.save(entity);
        return true;
    }

    public List<UserInfo> query() {
        List<TUsers> users =userDao.findAllUsers();
        List<UserInfo> userInfos = new ArrayList<>();

//        List<TUserrole> roles =  userRoleDao.findAll();
//        Map<Integer,String> rolesMap = new HashMap<>();
//        for(TUserrole role :roles){
//            rolesMap.put(role.getRoleid(),role.getRolename());
//        }
        for(TUsers user :users){
            UserInfo userInfo = transferUser(user, false) ;
            userInfo.setSys_rolename(UserType.getTypeName(userInfo.getSys_role()));
            userInfos.add(userInfo);
        }
        return userInfos ;
    }

    public TUsers one(int id) {
        if(userDao.exists(id)){
            return userDao.findOne(id);
        }
        return  null;
    }
    public List<TUsers> findByRoleid(int roleid){
        return userDao.findByTUserByRole(roleid);
    }


    /**
     * 批量导入用户
     *
     * @param path
     *          路径
     * @param sheetName
     *          sheet工作簿名
     * @param header_rows
     *          去除表头行数读
     * @param roleid
     *          roleid 添加的用户的角色id
     * @return
     */
    public Map<String,Object> importUser(String path,String sheetName,int header_rows,int roleid){
        Map<String,Object> re = new HashMap<String,Object>();

        List<List<Object>> dataList = ExcelUtil.readExcel(path,sheetName,header_rows);

        StringBuilder msg = new StringBuilder("导入成功！");
        if(dataList != null){

            TUserrole role = userRoleDao.findOne(roleid);   //找到角色

            int i = 1;
            for (List<Object> l : dataList){

                String userName = l.size()>0?l.get(0).toString():"";
                String caption = l.size()>1?l.get(1).toString():"";
                String password = l.size()>2?l.get(2).toString():"";
                String mail = l.size()>3?l.get(3).toString():"";
                String number = l.size()>4?l.get(4).toString():"";
                String department = l.size()>5?l.get(5).toString():"";
                String memo = l.size()>6?l.get(6).toString():"";
                if(userName.equals("")||password.equals("")){
                    msg.append("\r\n");
                    msg.append("第").append((i+1)).append("行，用户名或者密码不能为空");
                    continue;
                }
                if(userDao.findByUserName(userName) != null) { //用户名已经存在，不导入
                    msg.append("\r\n");
                    msg.append("第").append((i+1)).append("行，用户名【").append(userName).append("】已存在，未导入！");
                    continue;
                }
                TUsers tUsers = new TUsers();
                tUsers.setUserName(userName);
                tUsers.setUserCaption(caption);
                tUsers.setPassword(MD5Util.encode(password));    //MD5加密
                tUsers.setEmail(mail);
                tUsers.setPhone(number);
//                String phoneStr = null;
//                if(l.get(4) instanceof Double){
//                    phoneStr = ((Double)l.get(4)).longValue()+"";
//                }else{
//                    phoneStr = l.get(4).toString();
//                }
                tUsers.setUserPartment(department);
                tUsers.setMemo(memo);
                tUsers.setStatus(1);
//                tUsers.setSys_role(Role.OPERATOR.getRoleValue());   //默认为操作员
                userDao.save(tUsers);
                //若不为空，则创建统一角色
                if(role != null){
                    TUserrolerelation turla = new TUserrolerelation(tUsers,role);
                    userRoleRelationDao.save(turla);
                }
            }
        }

        re.put("status",true);
        re.put("msg",msg.toString());

        return re;
    }


    public boolean exportUser(){
        ArrayList<String>list = new ArrayList<String>();
        return  false;
    }

    /**
     * 按照Power找Users
     * @param powerid
     * @return
     */
    public List<TUsers> findUsersByPower(int powerid) {
        return userDao.findUsersByPower(powerid);
    }
    public  boolean checkUserNameExists(String userName){
        return userDao.findByUserName(userName)!=null?true:false;
    }

    /**
     * 根据MojorId找users
     */
    public List<TUsers> findByUserMajorId(int mid){
        return  userDao.findByTuserByMajor(mid);
    }

    /**
     * 获取用户的详细信息
     * @param userid
     * @return
     */
    public TUsers getUserInfos(int userid){
        TUsers user = userDao.findOne(userid);
        return  user;
    }

    /**
     * 获取用户的所有权限 系统权限 后台管理 数据权限
     * @param userid
     * @return
     */
    public Map<String,Object> getUserAllAuth(int userid){
        return  null ;
    }

    private UserInfo transferUser(TUsers user,boolean ismore){
        List<TUsermajor> majors = new ArrayList<>();
        if(ismore){
            majors =userMajorDao.findByUserId(user.getUserid());
        }
//        List<TRegioninfo>  regions = regionInfoDao.findByCode(user.getUserRegion());
//        String regionName = null!=regions&&regions.size()>0?regions.get(0).getName():"";
        return  new UserInfo(user,majors);
    }

    /**
     * 导入角色模板
     *
     * @return
     */
    public HSSFWorkbook downloadTemplate(){
        String[] head = new String[7] ;
        head[0] = "登录名" ;
        head[1] = "用户中文名" ;
        head[2] = "密码" ;
        head[3] = "电子邮件" ;
        head[4] = "联系电话" ;
        head[5] = "所在部门" ;
        head[6] = "备注" ;
        return  ExcelUtil.dataToWorkbook("用户导入模板",head,new String[0][]) ;
    }

    /**
     *
     * 设置指定用户的角色
     *
     * @param userid
     *          指定用户
     * @param roleids
     *          需要设置的权限
     * @return 返回设置的个数
     */
    public int setUserRolesByUserid(int userid,String roleids){
        int re = 0;

        TUsers tUsers = userDao.findOne(userid);
        if(tUsers != null){
            if (roleids != null && !roleids.isEmpty()){
                String[] roleIds = roleids.split(",");
                if(roleIds != null && roleIds.length > 0){
                    //先删除已存在的角色
                    int count = deleteAllUserRolesByUserid(userid);

                    for (int i=0,len=roleIds.length; i<len; i++){
                        if(roleIds[i] == null || roleIds[i].equals(""))
                            continue;
                        TUserrole tUserrole = userRoleDao.getOne(Integer.parseInt(roleIds[i]));
                        if(tUserrole != null){
                            userRoleRelationDao.save(new TUserrolerelation(tUsers,tUserrole));
                            re++;
                        }
                    }
                }//end if(roleIds != null && roleIds.length > 0)
            }
        }//end if(tUsers != null)

        return re;
    }

    /**
     * 删除指定用户下的所有角色
     * @param userid
     * @return
     */
    private int deleteAllUserRolesByUserid(int userid){
       String sql = "delete from T_USERROLERELATION t where t.userid=?";
       return userRoleRelationDao.executeBySql(sql,userid);
    }

}
